class Solution {
    public int myAtoi(String s) {
        s = s.trim();
        long num = 0;
        for (int i = (s.startsWith("-") || s.startsWith("+")) ? 1 : 0;
             i < s.length()
                     && s.charAt(i) >= '0' && s.charAt(i) <= '9'
                     && num >= Integer.MIN_VALUE && num <= Integer.MAX_VALUE; i++) {
            num = num * 10 + (s.charAt(i) - '0');
        }
        num = s.startsWith("-") ? -num : num;
        if (num < Integer.MIN_VALUE) {
            return Integer.MIN_VALUE;
        } else if (num > Integer.MAX_VALUE) {
            return Integer.MAX_VALUE;
        } else {
            return (int) num;
        }
    }
}